package mil.af.amc.adpetracker.web.actions.EquipmentItem;

import mil.af.amc.adpetracker.exceptions.DateFormatException;
import mil.af.amc.adpetracker.model.EquipmentItem;
import mil.af.amc.adpetracker.service.EquipmentItemService;
import mil.af.amc.adpetracker.service.ServiceException;
import mil.af.amc.adpetracker.service.UserService;
import mil.af.amc.adpetracker.service.exceptions.AdpeAccountNotFoundException;
import mil.af.amc.adpetracker.service.exceptions.ItemStatusNotFoundException;
import mil.af.amc.adpetracker.web.actions.AbstractDispatchAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Struts Actions having to do with EquipmentItem objects
 *
 * @author TSgt Jason Ferguson
 */

public class EquipmentItemDispatchAction extends AbstractDispatchAction {

    Log log = LogFactory.getLog(EquipmentItemDispatchAction.class);

    private EquipmentItemService equipmentItemService;

    public void setEquipmentItemService(EquipmentItemService equipmentItemService) {
        this.equipmentItemService = equipmentItemService;
    }

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public ActionForward viewDeleteItemPage(ActionMapping actionMapping,
                                            ActionForm actionForm,
                                            HttpServletRequest httpServletRequest,
                                            HttpServletResponse httpServletResponse) {

        return null;
    }

    public ActionForward importItems(ActionMapping actionMapping,
                                     ActionForm actionForm,
                                     HttpServletRequest httpServletRequest,
                                     HttpServletResponse httpServletResponse) {

        DynaActionForm importForm = (DynaActionForm) actionForm;
        FormFile importFile = (FormFile) importForm.get("equipmentFile");

        try {
            List<EquipmentItem> equipmentItemList = equipmentItemService.createMultipleItems(importFile.getFileData());
        } catch (AdpeAccountNotFoundException e) {

            log.debug("Imported file contained an unknown ADPE Account");
            ActionMessage actionMessage = new ActionMessage("error.adpeaccount.notfound");
            saveError(httpServletRequest, actionMessage);

            return actionMapping.findForward("failureImportItems");

        } catch (ItemStatusNotFoundException e) {

            log.debug("Imported file contained an unknown Item Status description", e);
            ActionMessage actionMessage = new ActionMessage("error.itemstatus.notfound");
            saveError(httpServletRequest, actionMessage);

            return actionMapping.findForward("failureImportItems");


        } catch (DateFormatException e) {

            log.debug("Imported file contained a badly formatted purchase date", e);
            ActionMessage actionMessage = new ActionMessage("error.equipmentitem.createitem.badpurchasedate", importForm.get("purchaseDate"));
            saveError(httpServletRequest, actionMessage);

            return actionMapping.findForward("failureImportItems");


        } catch (IOException e) {

            log.debug("Error opening file CSV file", e);
            ActionMessage actionMessage = new ActionMessage("error.csvfile.notfound");
            saveError(httpServletRequest, actionMessage);

            return actionMapping.findForward("failureImportItems");

        }

        return actionMapping.findForward("successImportItems");

        /*// Process the CSV File
        InputStream is = null;
        try {
            // Get an InputStream of the CSV file
            is = importFile.getInputStream();
            CsvReader csvReader = new CsvReader(is, Charset.forName("UTF-8"));
            csvReader.getHeaders();

            while (csvReader.readRecord()) {
                Map<String, String> itemMap = new HashMap<String, String>();
                itemMap.put("ipms", csvReader.get("IPMS Number"));
                itemMap.put("serialNumber", csvReader.get("Serial Number"));
                itemMap.put("manufacturer", csvReader.get("Manufacturer"));
                itemMap.put("model", csvReader.get("Model"));
                itemMap.put("description", csvReader.get("Description"));
                itemMap.put("equipmentType", csvReader.get("Equipment Type"));
                itemMap.put("purchaseDate", csvReader.get("Purchase Date"));
                itemMap.put("originalCost", csvReader.get("Original Cost"));
                //itemMap.put("assignedUserId", csvReader.get("Assigned User Id"));
                itemMap.put("location", csvReader.get("Location"));
                itemMap.put("adpeAccountId", csvReader.get("ADPE Account"));
                itemMap.put("itemStatusId", csvReader.get("Item Status"));

                try {
                    EquipmentItem item = equipmentItemService.createItem(itemMap);
                } catch (EquipmentItemExistsException e) {
                    log.debug("Tried to add a duplicate item", e);
                    ActionMessage actionMessage = new ActionMessage("error.equipmentitem.createitem.duplicate", importForm.get("serialNumber"));
                    saveError(httpServletRequest, actionMessage);
                } catch (DateFormatException e) {
                    log.debug("Tried to add a badly formatted date for purchase date", e);
                    ActionMessage actionMessage = new ActionMessage("error.equipmentitem.createitem.badpurchasedate", importForm.get("purchaseDate"));
                    saveError(httpServletRequest, actionMessage);

                    return actionMapping.findForward("failureCreateSingleItem");
                }

                is.close();
            }

        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return actionMapping.findForward("successImportItems");*/
    }

    public ActionForward delete(ActionMapping actionMapping,
                                ActionForm actionForm,
                                HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse) {

        int itemId = Integer.parseInt(httpServletRequest.getParameter("itemId"));
        EquipmentItem item = equipmentItemService.getById(itemId);

        if (item == null) {
            log.debug("Unable to delete EquipmentItem#" + itemId);
            ActionMessage actionMessage = new ActionMessage("error.delete.equipmentitem");
            saveError(httpServletRequest, actionMessage);

            return actionMapping.findForward("failureDeleteItem");

        }

        // TODO: Make sure the user is authorized to delete a certain item!

        equipmentItemService.delete(item);

        return actionMapping.findForward("success");
    }

    public ActionForward viewItemPage(ActionMapping actionMapping,
                                      ActionForm actionForm,
                                      HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse) {

        return actionMapping.findForward("viewItemPage");

    }

    public ActionForward unassignItem(ActionMapping actionMapping,
                                      ActionForm actionForm,
                                      HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse) {


        int itemId = Integer.parseInt(httpServletRequest.getParameter("itemId"));

        try {
            equipmentItemService.unassignItem(itemId);
        } catch (ServiceException e) {
            ActionMessage actionMessage = new ActionMessage(e.getKey());
            saveError(httpServletRequest, actionMessage);

            return actionMapping.getInputForward();

        }

        return actionMapping.getInputForward();
//        if (httpServletRequest.getParameter("inputPage").equals("viewByModel")) {
//            return actionMapping.findForward("viewEquipmentItemsByModel");
//        }
//
//        return actionMapping.findForward("viewAccountProfile");

    }

    public ActionForward viewEquipmentItemByModelPage(ActionMapping actionMapping,
                                                      ActionForm actionForm,
                                                      HttpServletRequest httpServletRequest,
                                                      HttpServletResponse httpServletResponse) {

        return actionMapping.findForward("viewEquipmentItemsByModel");
    }

    public ActionForward prepareEquipmentListView(ActionMapping actionMapping,
                                                  ActionForm actionForm,
                                                  HttpServletRequest httpServletRequest,
                                                  HttpServletResponse httpServletResponse) {

        return actionMapping.findForward("viewAccountProfile");

    }
}
